<template>
	<div class="layout-padding">
		<splitpanes>
			<pane class="ml8">
				<div class="layout-padding-auto layout-padding-view">
					<div v-show="showSearch">
						<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList" class="search-form-row">
							<el-row :gutter="10">
								<el-col :span="6">
									<el-form-item label="组态:" prop="scadaName">
										<el-input v-model="state.queryForm.scadaName" placeholder="组态名称" />
									</el-form-item>
								</el-col>
								<el-col :span="6">
									<el-form-item label="状态:" prop="bindFlag">
										<el-select v-model="state.queryForm.bindFlag" placeholder="请选中状态" clearable>
											<el-option label="启用" value="1"></el-option>
											<el-option label="未启用" value="2"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="6">
									<el-form-item>
										<el-button icon="Search" type="primary" @click="getDataList">{{ $t('common.queryBtn') }}</el-button>
										<el-button icon="Refresh" @click="resetQuery">{{ $t('common.resetBtn') }}</el-button>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
					</div>
					<el-row>
						<div class="mb8" style="width: 100%">
							<el-button v-auth="'scada_scadaProperty_add'" icon="folder-add" type="primary" @click="userDialogRef.openDialog()">
								{{ $t('common.addBtn') }}
							</el-button>

							<el-button
								plain
								v-auth="'scada_scadaProperty_del'"
								:disabled="multiple"
								class="ml10"
								icon="Delete"
								type="primary"
								@click="handleDelete(selectObjs)"
							>
								{{ $t('common.delBtn') }}
							</el-button>

							<right-toolbar
								v-model:showSearch="showSearch"
								@exportExcel="exportExcel"
								@queryTable="getDataList"
								class="ml10 mr20"
								style="float: right"
							>
								<el-tooltip effect="dark" content="卡片模式" placement="top">
									<el-button
										style="float: right"
										v-show="cardType === 'card'"
										circle
										icon="Grid"
										@click="cardType === 'card' ? (cardType = 'table') : (cardType = 'card')"
									/>
								</el-tooltip>
								<el-tooltip effect="dark" content="列表模式" placement="top">
									<el-button
										style="float: right"
										v-show="cardType === 'table'"
										circle
										icon="List"
										@click="cardType === 'card' ? (cardType = 'table') : (cardType = 'card')"
									/>
								</el-tooltip>
							</right-toolbar>
						</div>
					</el-row>
					<div class="card-container">
						<el-table
							v-loading="state.loading"
							:data="state.dataList"
							@selection-change="handleSelectionChange"
							row-key="userId"
							border
							:cell-style="tableStyle.cellStyle"
							:header-cell-style="tableStyle.headerCellStyle"
							v-show="cardType === 'table'"
						>
							<el-table-column :selectable="handleSelectable" type="selection" width="40" />
							<el-table-column :label="$t('sysuser.index')" type="index" width="60" fixed="left" />
							<el-table-column label="组态名称" prop="scadaName" fixed="left" show-overflow-tooltip></el-table-column>
							<el-table-column label="组态文件" prop="fileName" show-overflow-tooltip></el-table-column>
							<el-table-column label="状态" prop="bindFlag" show-overflow-tooltip>
								<template #default="{ row }">
									<div v-if="row.bindFlag == 2" class="text-color-yellow">未启用</div>
									<div v-else class="text-color-green">启用</div>
								</template>
							</el-table-column>
							<el-table-column label="组态图片" prop="imgName" show-overflow-tooltip></el-table-column>
							<el-table-column :label="$t('common.action')" width="400" fixed="right">
								<template #default="scope">
									<!-- 修改信息 -->
									<el-button v-auth="'scada_scadaProperty_edit'" icon="Edit" text type="primary" @click="userDialogRef.openDialog(scope.row)">
										{{ $t('common.editBtn') }}
									</el-button>
									<el-button icon="Setting" link type="primary" @click="deviceDialogRef.openDialog(scope.row, 'edit')">设备 </el-button>
									<el-button icon="View" @click="onOpenCheck(scope.row)" text type="primary" v-auth="'scada_scadaProperty_edit'">规则 </el-button>
									<el-button icon="Setting" link type="primary" @click="openSysConfig(scope.row)">参数</el-button>
									<el-button link icon="View" type="primary" @click="userDialogRef.openDialog(scope.row, 'detail')">查看 </el-button>
									<!-- 删除用户 -->
									<el-tooltip :content="$t('sysuser.deleteDisabledTip')" :disabled="scope.row.id !== '1'" placement="top">
										<span style="margin-left: 12px">
											<el-button icon="delete" v-auth="'scada_scadaProperty_del'" text type="primary" @click="handleDelete([scope.row.id])"
												>{{ $t('common.delBtn') }}
											</el-button>
										</span>
									</el-tooltip>
								</template>
							</el-table-column>
						</el-table>
						<!-- 卡片 -->
						<el-scrollbar>
							<div v-show="cardType === 'card'" class="cardClass">
								<el-card v-loading="state.loading" class="card" shadow="hover" v-for="item in state.dataList" :key="item.id">
									<el-row class="cardRow">
										<span class="cardTitle">{{ item.name }}</span>
									</el-row>
									<el-row>
										<el-col :span="16">
											<el-row class="cardRow">
												<span>组态名称: {{ item.scadaName }}</span>
											</el-row>
										</el-col>
										<el-col :span="8">
											<el-row>
												<div style="height: 100px; width: 100px">
													<img v-if="item.imgName" :src="baseURL + item.imageUrl" width="100px" height="100px" alt="" />
													<img v-else src="/@/assets/pic_device.png" width="100px" height="100px" alt="" />
												</div>
											</el-row>
										</el-col>
									</el-row>

									<template #footer>
										<div class="cardFooter">
											<el-button link type="primary" @click="userDialogRef.openDialog(item)">修改</el-button>
											<el-button link type="primary" @click="deviceDialogRef.openDialog(item, 'edit')">设备</el-button>
											<el-button link type="primary" @click="onOpenCheck(item)">规则 </el-button>
											<el-button link type="primary" @click="openSysConfig(item)">参数 </el-button>
											<el-button link type="primary" @click="userDialogRef.openDialog(item, 'detail')">查看</el-button>
											<el-button link type="primary" @click="handleDelete([item.id])">删除</el-button>
											<el-button link type="primary" style="cursor: default">
												<span v-if="item.bindFlag == 2" class="text-color-yellow">未启用</span>
												<span v-else class="text-color-green">启用</span>
											</el-button>
										</div>
									</template>
								</el-card>
								<el-empty v-if="state.dataList?.length == 0" description="暂无数据" />
							</div>
						</el-scrollbar>
					</div>
					<pagination v-bind="state.pagination" @current-change="currentChangeHandle" @size-change="sizeChangeHandle"> </pagination>
				</div>
			</pane>
		</splitpanes>

		<user-form ref="userDialogRef" @refresh="getDataList(false)" />
		<device-form ref="deviceDialogRef" />
		<el-dialog v-model="dialogSelectVisible" draggable title="查看规则" width="60%" :before-close="handleClose">
			<el-button type="primary" @click="handleAdd" style="margin-bottom: 10px">新增</el-button>
			<el-table :data="tableData" style="width: 100%" border>
				<el-table-column label="场景名称" prop="sceneName" show-overflow-tooltip />
				<el-table-column label="场景描述" prop="description" show-overflow-tooltip />
				<el-table-column label="触发方式" show-overflow-tooltip width="90">
					<template #default="scope">
						<div style="" v-if="scope.row.type == 0">设备</div>
						<div style="" v-if="scope.row.type == 1">定时</div>
					</template>
				</el-table-column>
				<el-table-column label="业务类型" width="90px">
					<template #default="scope">
						<div v-if="scope.row.actionType == 0">联动</div>
						<div v-if="scope.row.actionType == 1">告警</div>
					</template>
				</el-table-column>
				<el-table-column label="创建时间" prop="createTime" show-overflow-tooltip width="160" />
				<el-table-column label="运行状态" width="90px">
					<template #default="scope">
						<div v-if="scope.row.status == 1">
							<el-tag type="success">运行中</el-tag>
						</div>
						<div v-if="scope.row.status == 2"><el-tag type="danger">未启动</el-tag></div>
					</template>
				</el-table-column>
				<el-table-column width="140">
					<template #default="scope">
						<el-button icon="VideoPlay" @click="handleStartUp(scope.row)" text type="primary" v-if="scope.row.status == 2"> 启动 </el-button>
						<!-- 停止 -->
						<el-button icon="VideoPause" @click="handleStartUp(scope.row)" text type="primary" v-if="scope.row.status == 1"> 停止 </el-button>
						<!-- 触发 -->
						<el-button
							icon="RefreshRight"
							@click="beforeValidatePassword(scope.row.linkageId)"
							text
							type="primary"
							:disabled="scope.row.status == 1 ? false : true"
						>
							触发
						</el-button>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="290">
					<template #default="scope">
						<!-- <el-button icon="Edit" type="primary" text @click="handleEdit(scope.row)" :disabled="scope.row.status == 2 ? false : true">编辑</el-button> -->
						<el-button
							icon="Edit"
							type="primary"
							text
							@click="formDialogRef.openDialog(scope.row.linkageId, editParentId)"
							:disabled="scope.row.status == 2 ? false : true"
							>编辑</el-button
						>
						<el-button icon="View" @click="formDialogDetailsRef.openDialog(scope.row.linkageId)" text type="primary"
							>{{ $t('common.viewBtn') }}
						</el-button>
						<!-- 日志 -->
						<el-button icon="Document" @click="permessionRef.openDialog(scope.row.linkageId)" text type="primary"> 日志 </el-button>
						<!-- 删除 -->
						<el-button icon="delete" @click="handleRuleDelete(scope.row)" text type="primary" v-auth="'exsecs_sceneLinkage_del'">
							移除绑定
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- <template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogSelectVisible = false">取消</el-button>
					<el-button type="primary" @click="handleCheckSelectRule"> 关闭 </el-button>
				</div>
			</template> -->
		</el-dialog>

		<el-dialog v-model="dialogVisible" title="选择规则" draggable width="30%" :before-close="handleClose">
			<el-form
				ref="ruleFormRef"
				style="max-width: 600px"
				:model="ruleForm"
				:rules="rules"
				label-width="auto"
				class="demo-ruleForm"
				:size="formSize"
				status-icon
			>
				<el-form-item label="选择规则" prop="region">
					<el-select v-model="ruleForm.region" multiple clearable placeholder="请选择规则">
						<el-option v-for="(sele, index) in selectData" :key="index" :label="sele.sceneName" :value="sele.linkageId" />
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="handleCancel">取消</el-button>
					<el-button type="primary" @click="handleCheckRule"> 确认 </el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 详情 -->
		<form-dialog @refresh="getDataList()" ref="formDialogRef" />
		<Details-page @refresh="getDataList()" ref="formDialogDetailsRef" />
		<form-dialog-log @refresh="getDataList()" ref="permessionRef" />
		<el-dialog title="警告" v-model="showWarn" width="30%">
			<el-input v-model="password" type="password" placeholder="请输入密码校验" clearable style="margin-bottom: 20px"> </el-input>
			<span slot="footer" class="dialog-footer">
				<el-button @click="showWarn = false">取 消</el-button>
				<el-button type="primary" @click="validatePassword">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 系统参数绑定组态弹窗 -->
		<el-dialog title="系统参数绑定" v-model="showSysConfig" width="30%">
			<div class="condition-search">
				<div class="search-column" style="width: 200px">
					<el-input placeholder="请输入系统参数名称" clearable v-model="systemName" />
				</div>
				<div class="search-column">
					<el-button icon="Search" type="primary" @click="configQuery">{{ $t('common.queryBtn') }}</el-button>
					<el-button icon="Refresh" @click="resetConfigQuery">{{ $t('common.resetBtn') }}</el-button>
				</div>
			</div>
			<el-scrollbar height="300px">
				<el-tree
					ref="configTreeRef"
					style="max-width: 400px"
					check-strictly
					:data="configData"
					show-checkbox
					node-key="unitNo"
					:default-expand-all="true"
					:props="configDataProps"
				/>
			</el-scrollbar>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="showSysConfig = false">取消</el-button>
					<el-button type="primary" @click="handleConfigBind"> 确认 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" name="systemUser" setup>
import { delObj, pageList, queryCheckList, setScadaAndLinked, getListData, delRuleObj } from '/@/api/basiciot/iconfiguration/list';
import { updateStatus, getTrigger } from '/@/api/scene/sceneLinkage';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';
import { createRouter, createWebHistory, router } from 'vue-router';
import { checkPassword } from '/@/api/admin/user';
import { treeList, bindConfig, bindConfigDetail } from '/@/api/basiciot/iconfiguration/sysconfig';

// 动态引入组件
const UserForm = defineAsyncComponent(() => import('./form.vue'));
const DeviceForm = defineAsyncComponent(() => import('./device-bind.vue'));

const FormDialog = defineAsyncComponent(() => import('../../../../views/basiciot/ruleengine/scenelinkage/form.vue'));
const DetailsPage = defineAsyncComponent(() => import('../../../../views/basiciot/ruleengine/scenelinkage/details.vue'));
const FormDialogLog = defineAsyncComponent(() => import('../../../../views/basiciot/ruleengine/scenelinkage/formLog.vue'));

const cardType = ref('card');

const { t } = useI18n();

const showWarn = ref(false);
const password = ref('');
const triggerId = ref('');
// 定义变量内容
const userDialogRef = ref();
const deviceDialogRef = ref();
const queryRef = ref();
const showSearch = ref(true);

const openObjectModel = (row: any) => {
	useMessageBox()
		.confirm('是否启用该组态?')
		.then((res) => {})
		.catch(() => {});
};
const beforeValidatePassword = (val) => {
	showWarn.value = true;
	triggerId.value = val;
};
//验证密码
const validatePassword = async () => {
	if (!password.value) {
		password.value = '';
		useMessage().error('校验密码错误请重试');
		return false;
	}
	try {
		await checkPassword(password.value).then((res) => {
			showWarn.value = false;
			handleTrigger(triggerId.value);
		});
	} catch (e) {
		console.log(e);
		useMessage().error('校验密码错误请重试');
	} finally {
		password.value = '';
	}
};
// 多选rows
const selectObjs = ref([]) as any;
// 是否可以多选
const multiple = ref(true);
const formDialogRef = ref();
// 定义表格查询、后台调用的API
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
		scadaName: '',
		bindFlag: '',
	},
	pageList: pageList,
});
const { getDataList, currentChangeHandle, sizeChangeHandle, downBlobFile, tableStyle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
	queryRef.value?.resetFields();
	state.queryForm.scadaName = '';
	state.queryForm.bindFlag = '';
	getDataList();
};

// 导出excel
const exportExcel = () => {
	downBlobFile('/admin/user/export', Object.assign(state.queryForm, { ids: selectObjs }), 'users.xlsx');
};

// 是否可以多选
const handleSelectable = (row: any) => {
	return row.username !== 'admin';
};

// 多选事件
const handleSelectionChange = (objs: { id: string }[]) => {
	selectObjs.value = objs.map(({ id }) => id);
	multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm(t('common.delConfirmText'));
	} catch {
		return;
	}

	try {
		await delObj(ids);
		getDataList();
		useMessage().success(t('common.delSuccessText'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
// ---------
const ruleForm = reactive<RuleForm>({
	region: '',
	count: '',
});
const dialogSelectVisible = ref(false);
const dialogVisible = ref(false);
// 查看规则
let objData: any = ref({});
let editParentId = ref('');
const tableData: any = ref([]);
const onOpenCheck = (row) => {
	tableData.value = [];
	objData.value = row;
	editParentId.value = row.id;
	console.log(editParentId.value, 'editParentIdeditParentId');
	dialogSelectVisible.value = true;
	getListData({ current: 1, size: 999, parentId: row.id }).then((res1) => {
		queryCheckList({ current: 1, size: 999 }).then((res) => {
			let combinedArray = [];
			res1.data.records.forEach((item1) => {
				var aa = {};
				res.data.records.forEach((item2) => {
					if (item1.linkedId === item2.linkageId) {
						aa.detailsId = item1.id;
						aa.createBy = item1.createBy;
						aa.createTime = item1.createTime;
						aa.linkedId = item1.linkedId;
						aa.updateBy = item1.updateBy;
						aa.updateTime = item1.updateTime;
						let combinedItem = Object.assign({}, aa, item2);
						combinedArray.push(combinedItem);
					}
				});
			});
			tableData.value = combinedArray;
		});
	});
};
// 用于规则弹窗中操作后 刷新规则页面
const loadData = async () => {
	getListData({ current: 1, size: 999, parentId: objData._value.id }).then((res1) => {
		queryCheckList({ current: 1, size: 999 }).then((res) => {
			let combinedArray = [];
			res1.data.records.forEach((item1) => {
				var aa = {};
				res.data.records.forEach((item2) => {
					if (item1.linkedId === item2.linkageId) {
						aa.detailsId = item1.id;
						aa.createBy = item1.createBy;
						aa.createTime = item1.createTime;
						aa.linkedId = item1.linkedId;
						aa.updateBy = item1.updateBy;
						aa.updateTime = item1.updateTime;
						let combinedItem = Object.assign({}, aa, item2);
						combinedArray.push(combinedItem);
					}
				});
			});
			tableData.value = combinedArray;
		});
	});
};
// const handleCheckSelectRule = async () => {
// 	tableData.value = [];
// 	dialogSelectVisible.value = false;
// };
let selectData: any = ref([]);
const handleAdd = async () => {
	dialogVisible.value = true;
	queryCheckList({ current: 1, size: 999 }).then((res) => {
		selectData.value = res.data.records;
		getListData({ current: 1, size: 999, parentId: objData._value.id }).then((res1) => {
			ruleForm.region = res1.data.records.map((item) => item.linkedId);
			// tableData.value = res1.data.records;
		});
		// ruleForm.region = tableData.value.map((item) => item.linkedId);
	});
};
// 查看规则 确认
const handleCheckRule = async () => {
	var linkData = [];
	ruleForm.region.map((item) => {
		var linkObj = {};
		linkObj.parentId = objData._value.id;
		linkObj.linkedId = item;
		linkObj.id = '';
		linkData.push(linkObj);
	});
	await setScadaAndLinked(linkData);
	selectData.value = [];
	loadData();
	dialogVisible.value = false;
};
const handleCancel = async () => {
	selectData.value = [];
	dialogVisible.value = false;
};
const router = useRouter();
const handleEdit = async (val) => {
	router.push({
		path: '/basiciot/ruleengine/scenelinkage/index',
		query: {
			linkageId: val.linkageId,
			id: val.detailsId,
		},
	});
};
const permessionRef = ref();
const formDialogDetailsRef = ref(); // 详情
// 删除操作
const handleRuleDelete = async (val: string) => {
	try {
		await useMessageBox().confirm(t('此操作将移除绑定'));
	} catch {
		return;
	}
	try {
		await delRuleObj(val.detailsId);
		loadData();
		useMessage().success(t('common.delSuccessText'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

// 启动 / 启动
const handleStartUp = async (val) => {
	try {
		await useMessageBox().confirm(t('确认要执行该操作吗？'));
	} catch {
		return;
	}
	try {
		await updateStatus({
			linkageId: val.linkageId,
			status: val.status == 2 ? '1' : '2',
		});
		loadData();
		useMessage().success(t('操作成功'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
// 触发
const handleTrigger = async (val) => {
	try {
		await getTrigger(val);
		loadData();
		useMessage().success(t('触发成功'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
//系统参数配置
const showSysConfig = ref(false);
const scadaId = ref('');
const configTreeRef = ref();
const openSysConfig = (obj) => {
	showSysConfig.value = true;
	scadaId.value = obj.id;
	queryConfig();
};
// 搜索事件
const configData = ref([]);
const queryConfig = () => {
	configData.value = [];
	treeList({
		systemName: systemName.value,
	}).then((res) => {
		configData.value = digui(res.data);
	});
	configTreeRef.value.setCheckedKeys([]);
	bindConfigDetail({
		scadaId: scadaId.value,
	}).then((res) => {
		if (res.data?.length > 0) {
			configTreeRef.value.setCheckedKeys(res.data);
		}
	});
};
//递归给树形数据加disabled属性
const digui = (arr) => {
	let result = [];
	arr.forEach((item) => {
		if (item.type == '文件夹') {
			item.disabled = true;
		} else {
			item.disabled = false;
		}
		result.push(item);
		if (item.children) {
			digui(item.children);
		}
	});
	return result;
};
const configDataProps = {
	label: 'name',
	children: 'children',
	disabled: 'disabled',
};
const systemName = ref('');
const configQuery = () => {
	queryConfig();
};
// 清空搜索条件
const resetConfigQuery = () => {
	systemName.value = '';
	queryConfig();
};
//组态绑定系统参数
const handleConfigBind = () => {
	bindConfig({
		scadaId: scadaId.value,
		unitNos: configTreeRef.value.getCheckedKeys(),
	}).then((res) => {
		useMessage().success(t('绑定成功'));
		showSysConfig.value = false;
	});
};
</script>
<style lang="scss" scoped>
.condition-search {
	display: flex;
	margin-bottom: 10px;
	.search-column {
		margin-right: 10px;
	}
}
.card-container {
	min-height: vh(580);
	text-align: center;
}
.cardClass {
	display: flex;
	flex-wrap: wrap;
	overflow-y: scroll;
	:deep(.card) {
		width: 24%;
		// height: 230px;
		margin: 0 15px 15px 0;
		.el-card__body {
			min-height: 100px;
		}
	}

	.cardRow {
		margin-bottom: 10px;
	}
	.cardTitle {
		font-size: 16px;
		font-weight: 600;
	}
	.cardFooter {
		display: flex;
		justify-content: space-between;
	}
}
.el-empty {
	margin: 0 auto;
}
.dialog-footer {
	display: flex;
	justify-content: flex-end;
}
.text-color-yellow {
	color: var(--el-color-warning);
}
.text-color-green {
	color: var(--el-color-success);
}
</style>
